<template>
  <div class="home-page">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="greeting">
        <h1>欢迎使用智护童行</h1>
        <p>关爱儿童健康，助力快乐成长 🌟</p>
      </div>
      <div class="quick-actions">
        <el-button type="primary" round @click="goToGrowthRecord">
          <el-icon><Edit /></el-icon>记录成长
        </el-button>
        <el-button type="success" round @click="goToConsult">
          <el-icon><Service /></el-icon>咨询医生
        </el-button>
      </div>
    </div>

    <!-- 功能卡片区 -->
    <div class="feature-grid">
      <div class="feature-card growth">
        <div class="card-content">
          <el-icon class="feature-icon"><TrendCharts /></el-icon>
          <h3>成长记录</h3>
          <p>记录身高体重，追踪成长轨迹</p>
          <el-button type="primary" plain round @click="goToGrowthRecord">立即记录</el-button>
        </div>
      </div>

      <div class="feature-card consult">
        <div class="card-content">
          <el-icon class="feature-icon"><ChatDotRound /></el-icon>
          <h3>在线问诊</h3>
          <p>专业医生在线解答，守护健康成长</p>
          <el-button type="success" plain round @click="goToConsult">去咨询</el-button>
        </div>
      </div>

      <div class="feature-card vaccine">
        <div class="card-content">
          <el-icon class="feature-icon"><FirstAidKit /></el-icon>
          <h3>疫苗接种</h3>
          <p>科学规划接种时间，预防疾病</p>
          <el-button type="warning" plain round @click="goToHealth">查看计划</el-button>
        </div>
      </div>

      <div class="feature-card nutrition">
        <div class="card-content">
          <el-icon class="feature-icon"><Food /></el-icon>
          <h3>营养建议</h3>
          <p>合理膳食搭配，助力健康成长</p>
          <el-button type="info" plain round @click="goToEducation">了解更多</el-button>
        </div>
      </div>
      <div class="feature-card selfcheck">
        <div class="card-content">
          <el-icon class="feature-icon"><Search /></el-icon>
          <h3>自检助手</h3>
          <p>快速健康自检，及时发现潜在问题</p>
          <el-button type="danger" plain round @click="goToSelfCheck">开始自检</el-button>
        </div>
      </div>
      <div class="feature-card navigation">
        <div class="card-content">
          <el-icon class="feature-icon"><Location /></el-icon>
          <h3>医院导航</h3>
          <p>查找附近医院，快速就医不迷路</p>
          <el-button type="primary" plain round @click="goToHospitalNav">查找医院</el-button>
        </div>
      </div>
    </div>

    <!-- 健康小贴士 -->
    <div class="tips-section">
      <h2>健康小贴士</h2>
      <div class="tips-grid">
        <div class="tip-card">
          <el-icon class="tip-icon"><Sunny /></el-icon>
          <h4>户外活动</h4>
          <p>每天1小时户外活动，增强抵抗力</p>
        </div>
        <div class="tip-card">
          <el-icon class="tip-icon"><MoonNight /></el-icon>
          <h4>充足睡眠</h4>
          <p>保证充足睡眠，促进身体发育</p>
        </div>
        <div class="tip-card">
          <el-icon class="tip-icon"><Apple /></el-icon>
          <h4>均衡饮食</h4>
          <p>营养均衡搭配，助力健康成长</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { 
  Edit, 
  Service,
  TrendCharts,
  ChatDotRound,
  FirstAidKit,
  Food,
  Sunny,
  MoonNight,
  Apple
} from '@element-plus/icons-vue'

const router = useRouter()

const goToConsult = () => {
  router.push('/user/consult')
}

const goToGrowthRecord = () => {
  router.push('/user/growth')
}
const goToHealth = () => {
  router.push('/user/health')
}
const goToEducation = () => {
  router.push('/user/education')
}
const goToSelfCheck = () => {
  router.push('/user/selfcheck')
}
// 新增的医院导航路由
const goToHospitalNav = () => {
  router.push('/user/hospitalNav')
}
// 切换选中的儿童
const handleChildChange = async (childId) => {
  selectedChild.value = childId
  // 重置数据为默认值
  latestGrowth.value = {
    height: 0,
    weight: 0,
    bmi: 0,
    heightDiff: 0,
    weightDiff: 0,
    bmiDiff: 0
  }
  chartLoading.value = true
  
  try {
    const data = await get(`/user/growth/latest/${childId}`)
    if (data && Object.keys(data).length > 0) {
      latestGrowth.value = data
    }
    await fetchGrowthData(childId)
  } catch (error) {
    console.error('获取生长数据失败:', error)
  } finally {
    chartLoading.value = false
  }
}

// 获取生长记录数据
const fetchGrowthData = async (childId) => {
  try {
    const data = await get(`/user/growth/list/${childId}`)
    if (data && data.length > 0) {
      // 处理图表数据
      const dates = data.map(item => formatDate(item.measureDate))
      const heights = data.map(item => item.height)
      const weights = data.map(item => item.weight)
      
      chartData.value = {
        dates,
        heights,
        weights
      }
      initChart()
    } else {
      // 没有历史数据时，显示空的图表
      chartData.value = {
        dates: [],
        heights: [],
        weights: []
      }
      chartInstance?.clear()
      chartInstance?.showLoading({
        text: '暂无历史记录',
        maskColor: 'rgba(255, 255, 255, 0.8)',
        fontSize: 14,
        showSpinner: false,
        color: '#909399'
      })
    }
  } catch (error) {
    console.error('获取生长记录列表失败:', error)
    chartInstance?.clear()
    chartInstance?.showLoading({
      text: '暂无历史记录',
      maskColor: 'rgba(255, 255, 255, 0.8)',
      fontSize: 14,
      showSpinner: false,
      color: '#909399'
    })
  }
}

// 初始化图表
const initChart = () => {
  if (!chartInstance || !chartData.value) return
  
  const option = {
    title: {
      text: chartData.value.dates.length ? '生长记录趋势' : '暂无历史记录',
      left: 'center',
      textStyle: {
        color: chartData.value.dates.length ? '#333' : '#909399',
        fontSize: chartData.value.dates.length ? 16 : 14
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        if (!params.length) return '暂无数据'
        let result = params[0].axisValue + '<br/>'
        params.forEach(param => {
          const value = param.value === undefined ? '0' : param.value
          result += param.marker + param.seriesName + ': ' + value + (param.seriesName === '身高' ? 'cm' : 'kg') + '<br/>'
        })
        return result
      }
    },
    legend: {
      data: ['身高', '体重'],
      bottom: '5%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        name: '身高(cm)',
        type: 'value',
        position: 'left',
        min: 0
      },
      {
        name: '体重(kg)',
        type: 'value',
        position: 'right',
        min: 0
      }
    ],
    series: [
      {
        name: '身高',
        type: 'line',
        data: chartData.value.heights,
        yAxisIndex: 0,
        itemStyle: {
          color: '#409EFF'
        },
        smooth: true
      },
      {
        name: '体重',
        type: 'line',
        data: chartData.value.weights,
        yAxisIndex: 1,
        itemStyle: {
          color: '#67C23A'
        },
        smooth: true
      }
    ]
  }
  
  chartInstance.setOption(option)
  chartInstance.hideLoading()
}
</script>

<style scoped>
.home-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.welcome-section {
  background: linear-gradient(135deg, #4b6cb7 0%, #182848 100%);
  color: white;
  padding: 40px;
  border-radius: 20px;
  margin-bottom: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.greeting h1 {
  font-size: 28px;
  margin: 0;
  margin-bottom: 12px;
  font-weight: 600;
}

.greeting p {
  margin: 0;
  opacity: 0.9;
  font-size: 16px;
}

.quick-actions {
  display: flex;
  gap: 16px;
}

.quick-actions .el-button {
  padding: 12px 24px;
  font-size: 16px;
}

.feature-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.feature-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  height: 100%;
  min-height: 240px;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.card-content {
  padding: 32px;
  text-align: center;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.feature-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.growth .feature-icon {
  color: #409eff;
}

.consult .feature-icon {
  color: #67c23a;
}

.vaccine .feature-icon {
  color: #e6a23c;
}

.nutrition .feature-icon {
  color: #909399;
}

.card-content h3 {
  margin: 0 0 12px;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.card-content p {
  margin: 0 0 24px;
  color: #666;
  line-height: 1.6;
}

.tips-section {
  background: white;
  border-radius: 20px;
  padding: 32px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.tips-section h2 {
  text-align: center;
  margin: 0 0 24px;
  font-size: 24px;
  color: #333;
}

.tips-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 24px;
}

.tip-card {
  text-align: center;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.tip-card:hover {
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.tip-icon {
  font-size: 32px;
  margin-bottom: 16px;
  color: #409eff;
}

.tip-card h4 {
  margin: 0 0 8px;
  font-size: 18px;
  color: #333;
}

.tip-card p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

:deep(.el-button) {
  padding: 12px 24px;
  font-size: 14px;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #4b6cb7 0%, #182848 100%);
  border: none;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #67c23a 0%, #4caf50 100%);
  border: none;
}

.feature-card.consult .el-button {
  background: linear-gradient(135deg, #95de64 0%, #52c41a 100%);
  border: none;
  color: #ffffff;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.feature-card.consult .el-button:hover {
  background: linear-gradient(135deg, #b7eb8f 0%, #73d13d 100%);
}
</style> 